package cn.jiedh.app.meiweidk.mine;

import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.tauth.Tencent;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.UI.AlertDialog;
import cn.jiedh.app.meiweidk.Utils.UI.EmptyRecyclerView;
import cn.jiedh.app.meiweidk.Utils.UI.StateLayout;
import cn.jiedh.app.meiweidk.Utils.tool.SPUtils;
import cn.jiedh.app.meiweidk.Utils.tool.UrlUtils;
import cn.jiedh.app.meiweidk.app.AppConstant;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.baseadapter.BaseAdapter;
import cn.jiedh.app.meiweidk.baseadapter.BaseViewHolder;
import cn.jiedh.app.meiweidk.entity.ApplicationInfoBean;
import cn.jiedh.app.meiweidk.network.ResponseSuccess;
import cn.jiedh.app.meiweidk.response.BaseResponse;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionHelper;

/**
 * @name：
 * @author： liuyun
 * @phone： 15723310658
 * @createTime： 2017/12/12
 * @modifyTime： 2017/12/12
 * @explain：说明
 */


public class NewChatActivity extends BaseActivity {
    private static final int PERMISSION_QQ = 1;//qq加群权限
    @BindView(R.id.bar_tv_title)
    TextView barTvTitle;
    @BindView(R.id.listview)
    EmptyRecyclerView listview;
    @BindView(R.id.empty_nn_pic)
    ImageView emptyNnPic;
    @BindView(R.id.empty_nn_btn)
    TextView emptyNnBtn;
    @BindView(R.id.statelayout)
    StateLayout statelayout;
    @BindView(R.id.smartrefreshLayout)
    SmartRefreshLayout smartrefreshLayout;

    BaseAdapter<ChatBean> adapter;
    List<ChatBean> list = new ArrayList<>();
    Tencent mTencent;
    @BindView(R.id.bar_img_back)
    ImageView barImgBack;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_new_chat;
    }

    @Override
    protected void initView(View view) {
        barTvTitle.setText("助贷交流群");

//        list.add(new ChatBean());
//        list.add(new ChatBean());
//        list.add(new ChatBean());
        statelayout.setOnNoClick(view12 -> smartrefreshLayout.autoRefresh());
        adapter = new BaseAdapter<ChatBean>(this, R.layout.item_new_chat_center, list) {
            @Override
            public void convert(BaseViewHolder holder, ChatBean info, int position) {
                if (info.getType() == 0) {//qq
                    holder.setImageRes(R.id.logo_iv, R.drawable.icon_qq);
                    holder.setText(R.id.name_tv, "QQ群号");
                    holder.setText(R.id.num_chat, info.getShowNum());
                    if (!TextUtils.isEmpty(info.getQqKey())) {
                        holder.setVisibility(R.id.add_group, true);
                        holder.setVisibility(R.id.click_copy, false);
                    } else {
                        holder.setVisibility(R.id.add_group, false);
                        holder.setVisibility(R.id.click_copy, true);
                    }
                } else {//wechat
                    holder.setImageRes(R.id.logo_iv,R.drawable.icon_wechat);
                    holder.setText(R.id.name_tv, "微信公众号");
                    holder.setText(R.id.num_chat, info.getShowNum());
                    holder.setVisibility(R.id.add_group, false);
                    holder.setVisibility(R.id.click_copy, true);
                }
                View.OnClickListener clickListener = new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.add_group:
                                MobclickAgent.onEvent(activity,"my_service_qq_click");
                                SPUtils.saveBuried("click","0","助贷服务-助贷交流群号码点击","",
                                        "我的-助贷服务","","","");
                                mTencent.joinQQGroup(NewChatActivity.this, info.getQqKey());
                                break;
                            case R.id.click_copy:
                                MobclickAgent.onEvent(activity,"my_service_wechat_click");
                                SPUtils.saveBuried("click","0","助贷服务-公众号点击","",
                                        "我的-助贷服务","","","");
                                //获取剪贴板管理器：
                                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                                // 创建普通字符型ClipData
                                ClipData mClipData = ClipData.newPlainText("微信公众号", info.getShowNum());
                                // 将ClipData内容放到系统剪贴板里。
                                cm.setPrimaryClip(mClipData);

                                AlertDialog dialog=new AlertDialog(activity);
                                dialog.builder();
                                dialog.setTitle("权限申请");
                                dialog.setMsg("微信号“"+info.getShowNum()+"”已复制，直接粘贴到微信，搜索并关注公众号");
                                dialog.setNegativeButton("取消",null);
                                dialog.setPositiveButton("打开微信", new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        openWeChat();
                                    }
                                });

                                dialog.show();
                                break;
                        }
                    }
                };
                holder.setOnclickListener(R.id.add_group, clickListener);
                holder.setOnclickListener(R.id.click_copy, clickListener);

            }
        };
        listview.setLayoutManager(new LinearLayoutManager(this));
        listview.setAdapter(adapter);
        smartrefreshLayout.autoRefresh();
        smartrefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        smartrefreshLayout.setOnRefreshListener(refreshLayout -> refreshLayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                statelayout.netviewGone();
                getData();
                refreshLayout.finishRefresh();
            }
        }, 2000));
    }

    public void getData() {

        request(this, UrlUtils.GETAPPLICATIONINFO, new HashMap<>(), false, new ResponseSuccess<ApplicationInfoBean>() {
            @Override
            public void onRequestSucceed(BaseResponse<ApplicationInfoBean> response) {
                if (response.getCode() == 0) {
                    ApplicationInfoBean info = response.getData();
                    list.clear();
                    list.addAll(getListByInfo(info));
                    listview.setEmptyView(findViewById(R.id.emptyview));
                    adapter.notifyDataSetChanged();
                }
            }
        }, (error, msg) -> {
            statelayout.netviewGone();
            list.clear();
            listview.setEmptyView(findViewById(R.id.emptyview));
            adapter.notifyDataSetChanged();
        });
    }

    private List<ChatBean> getListByInfo(ApplicationInfoBean info) {
        List<ChatBean> beens = new ArrayList<>();
        if (info != null) {
            if (!TextUtils.isEmpty(info.getQqGroup())) {
                String[] qqs = info.getQqGroup().split(",");
                String[] qqKeys = !TextUtils.isEmpty(info.getQqGroupKey()) ? info.getQqGroupKey().split(",") : new String[]{};
                if (qqs != null && qqs.length > 0) {
                    for (int i = 0; i < qqs.length; i++) {
                        ChatBean chatBean = new ChatBean(0, qqs[i], qqKeys.length > i ? qqKeys[i] : null);
                        beens.add(chatBean);
                    }
                }
            }
            if (!TextUtils.isEmpty(info.getWechatPublic())) {
                beens.add(new ChatBean(1, info.getWechatPublic(), null));
            }
        }
        return beens;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        mTencent = Tencent.createInstance(AppConstant.UMENG_QQ_ID, this.getApplicationContext());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        Tencent.onActivityResultData(requestCode,resultCode,data,listener);
    }

    @Override
    public void onRequestPermissionsResult(final int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionHelper.requestPermissionsResult(requestCode, permissions, grantResults, permissionResult);
    }

    PermissionHelper.PermissionResult permissionResult = new PermissionHelper.PermissionResult() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PERMISSION_QQ:
                    mTencent.joinQQGroup(NewChatActivity.this, "650902724");
                    break;

            }
        }

        @Override
        public void onPermissionDenied(int requestCode, String... noPermissions) {
            switch (requestCode) {
//                case PERMISSION_READ_PHONE_STATE:
//                    mCountDownTimer.start();
//                    initNetData();
//                    break;
                case PERMISSION_QQ:
                    Toast.makeText(NewChatActivity.this, ".............", Toast.LENGTH_LONG).show();
                    break;

            }
        }
    };
    private void openWeChat() {
        if(isWXAppInstalled()){
            try {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");

                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(cmp);
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(this, "检查到您手机没有安装微信，请安装后使用该功能", Toast.LENGTH_LONG).show();

            }
        }else{
            Toast.makeText(this, "检查到您手机没有安装微信，请安装后使用该功能", Toast.LENGTH_LONG).show();
        }
    }
    public final boolean isWXAppInstalled() {
        try {
            return getPackageManager().getPackageInfo("com.tencent.mm", PackageManager.GET_SIGNATURES) != null;
        } catch (PackageManager.NameNotFoundException var2) {
            return false;
        }
    }
}
